package cus179.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import cus179.config.InitConfig;
import cus179.config.UkeyProperties;
import cus179.dto.SignRequest;
import cus179.dto.SignResult;
import cus179.dto.WebSocketWrapper;
import cus179.entity.Cus179DataUpVo;
import cus179.handler.WebSocketClientHandler;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;

import javax.annotation.Resource;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.LockSupport;

/**
 * @author 周鑫
 * @version 1.0.0
 * @Description TODO
 * @createTime 2024年02月22日 10:15
 */
@Slf4j
@RestController
public class TestController {

    @Resource
    private StandardWebSocketClient standardWebSocketClient;
    @Resource
    private WebSocketClientHandler webSocketClientHandler;
    @Resource
    private UkeyProperties properties;

    /**
     * 179加签并推送海关
     */
    @GetMapping("/cus179test")
    public void cus179test() {
        //179
        String cus179String = "  {\"sessionID\":\"fe2374-8fnejf97-55616242\",\"payExchangeInfoHead\":{\"guid\":\"9D55BA71-55DE-41F4-8B50-C36C83B3B419\",\"initalRequest\":\"<xml><appid>wx6ca5234a7c957393</appid><mch_id>1240066702</mch_id><device_info>WEB</device_info><nonce_str>slfdow8mjvcyg8ziwwrjp74hxvdj1un9</nonce_str><sign>3F61F479091ECF04C07EBA7F429EA5FE</sign><body>荷兰牛栏Nutrilon深度水解抗敏2段</body><attach>10000002504751</attach><out_trade_no>Hi2019041414381952500007331</out_trade_no><total_fee>64389</total_fee><spbill_create_ip>172.16.22.100</spbill_create_ip><time_start></time_start><time_expire></time_expire><goods_tag></goods_tag><notify_url>http://gw.hipac.cn/pub/WEIXIN02010302/transNotify.do</notify_url><trade_type>JSAPI</trade_type><product_id>10524</product_id><openid>okMv5s3Y8XAF10xVPACfr00sdmFM</openid></xml>\",\"initalResponse\":\"<xml><appid><![CDATA[wx6ca5234a7c957393]]></appid><attach><![CDATA[10000002504751]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[64389]]></cash_fee><device_info><![CDATA[WEB]]></device_info><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[N]]></is_subscribe><mch_id><![CDATA[1240066702]]></mch_id><nonce_str><![CDATA[d382t2u7j89oy6c5t4hlgq5374nqhso9]]></nonce_str><openid><![CDATA[okMv5s3Y8XAF10xVPACfr00sdmFM]]></openid><out_trade_no><![CDATA[Hi2019041414381952500007331]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[3C27DCFFFBFD53549154B17F9183578E]]></sign><time_end><![CDATA[20190414143823]]></time_end><total_fee>64389</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4200000302201904149212202113]]></transaction_id></xml>\",\"ebpCode\":\"3301234K11\",\"payCode\":\"312226T001\",\"payTransactionId\":\"Hi2019041414381952500001234\",\"totalAmount\":643.89,\"currency\":\"142\",\"verDept\":\"2\",\"payType\":\"1\",\"tradingTime\":\"20190414143823\",\"note\":\"\"},\"payExchangeInfoLists\":[{\"orderNo\":\"30001904141431271234\",\"goodsInfo\":[{\"gname\":\"荷兰牛栏Nutrilon深度水解抗敏2段\",\"itemLink\":\"http://prec.hipac.cn/pub/weidian/wxdGoods/itemDetail.do?itemId=10524&shopId=ff00888e666f41a09b5dad39473ead87\"}],\"recpAccount\":\"\",\"recpCode\":\"\",\"recpName\":\"CHAIN MANAGEMENT\"}],\"serviceTime\":\"1555558003200\",\"certNo\":\"01371bf2\",\"signValue\":\"cdkIadlRSHZU9HyVenhIOI2thrq9hocPAzKiE0f9GC9nm6qaVbSRqFTNFVVZR0FpwZoXpVSNqHXUGuDjBlNSnqRY7LNWLW8dl+Ytu1XyKoWfArcuAg63WA9FdlbZ/nGK+gJqU80J4URk5GSG1paR98eqwtZSWinuCmj3tq8c2qU=\"}";
        SignRequest request = new SignRequest();
        Cus179DataUpVo cus179DataUpVo = JSON.parseObject(cus179String, Cus179DataUpVo.class);
        String sign179String = "\"sessionID\":\"" + cus179DataUpVo.getSessionID() + "\"" +
                "||\"payExchangeInfoHead\":\"" + JSON.toJSONString(cus179DataUpVo.getPayExchangeInfoHead()) + "\"" +
                "||\"payExchangeInfoLists\":\"" + JSONArray.toJSONString(cus179DataUpVo.getPayExchangeInfoLists()) + "\"" +
                "||\"serviceTime\":\"" + cus179DataUpVo.getServiceTime() + "\"";
        request.setId(1);
        request.setData(sign179String);

        WebSocketWrapper wrapper = webSocketClientHandler.getWebSocketWrapper();
        wrapper.setPayload(InitConfig.getSignDataAsPEMParameter(request));
        wrapper.setRequest(request);
        wrapper.setSignResult(new SignResult());
        wrapper.setThreadReference(new AtomicReference<>(Thread.currentThread()));
        WebSocketConnectionManager manager = new WebSocketConnectionManager(standardWebSocketClient, webSocketClientHandler, properties.getWsUrl());
        manager.start();

        try {
            LockSupport.parkNanos(wrapper.getThreadReference(), 1000 * 1000 * 1000 * 5L);
        } catch (Exception e) {
            log.error("线程自动unpark异常 {}", e.getLocalizedMessage(), e);
            wrapper.getSignResult().setSuccess(false);
        } finally {
            manager.stop();
        }
        cus179DataUpVo.setSignValue(wrapper.getSignResult().getSignatureValue());

        //发送报文
        //设置超时时间
        Unirest.setTimeouts(0, 3000);
        try {
            HttpResponse<String> response = Unirest.post("https://customs.chinaport.gov.cn/ceb2grab/grab/realTimeDataUpload")
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .field("payExInfoStr", JSON.toJSONString(cus179DataUpVo))
                    .asString();
            log.info("海关响应：{}", response.getBody());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
